﻿package framework.core;


import java.text.NumberFormat;
import java.util.*;

import javax.servlet.http.*;



/**
 * 此处插入类型描述。
 * 创建日期：(2002-11-6 17:14:00)
 * @author：Administrator
 */
public class StringUtil {

    /**
    * StringFactory 构造子注解。
    */
    public StringUtil() {
        super();
    }
    /**
     *  填充位数
     *
     *@param  str  The feature to be added to the Zero attribute
     *@param  i    The feature to be added to the Zero attribute
     *@return      Description of the Returned Value
     */
    public static String addZero(String str, int i) {
        String strTemp = "";
        for (int j = str.length(); j < i; j++) {
            strTemp = strTemp + "0";
        }
        return strTemp + str;
    }
    /**
     * 此处插入方法描述。
     * 创建日期：(2002-4-1 11:29:43)
     * @return java.lang.String
     * @param excelDate java.lang.String
     */
    public static String changeExcelDate(String excelDate) throws Exception {

        try {

            if (excelDate == null)
                throw new Exception("excel date is null");

            int sepMonth = excelDate.indexOf("-");
            int sepYear = excelDate.indexOf("-", sepMonth + 1);

            String strDay = excelDate.substring(0, sepMonth);
            String strMonth = excelDate.substring(sepMonth + 1, sepYear);
            String strYear = excelDate.substring(sepYear + 1, excelDate.length());

            if (strMonth.equalsIgnoreCase("Jan")) {
                strMonth = "01";
            }
            if (strMonth.equalsIgnoreCase("Feb")) {
                strMonth = "02";
            }
            if (strMonth.equalsIgnoreCase("Mar")) {
                strMonth = "03";
            }
            if (strMonth.equalsIgnoreCase("Apr")) {
                strMonth = "04";
            }
            if (strMonth.equalsIgnoreCase("May")) {
                strMonth = "05";
            }
            if (strMonth.equalsIgnoreCase("Jun")) {
                strMonth = "06";
            }
            if (strMonth.equalsIgnoreCase("Jul")) {
                strMonth = "07";
            }
            if (strMonth.equalsIgnoreCase("Aug")) {
                strMonth = "08";
            }
            if (strMonth.equalsIgnoreCase("Sep")) {
                strMonth = "09";
            }
            if (strMonth.equalsIgnoreCase("Oct")) {
                strMonth = "10";
            }
            if (strMonth.equalsIgnoreCase("Nov")) {
                strMonth = "11";
            }
            if (strMonth.equalsIgnoreCase("Dec")) {
                strMonth = "12";
            }

            if (strYear.equals("98")) {
                strYear = "1998";
            } else
                if (strYear.equals("99")) {
                    strYear = "1999";
                } else
                    if (strYear.equals("00")) {
                        strYear = "2000";
                    } else
                        if (strYear.equals("01")) {
                            strYear = "2001";
                        } else
                            if (strYear.equals("02")) {
                                strYear = "2002";
                            } else
                                if (strYear.equals("03")) {
                                    strYear = "2003";
                                } else {
                                    strYear = "19" + strYear;
                                }

            int intYear = Integer.parseInt(strYear);
            int intMonth = Integer.parseInt(strMonth);
            int intDay = Integer.parseInt(strDay);

            DateUtil dt = new DateUtil(intYear, intMonth, intDay, 0, 0, 0);

            return dt.getDateString();
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     *  判断是否在vector中存在此字符串
     *
     *@return    ture/false
     */
    public static boolean existCodeInVector(
        java.util.Vector vVector,
        String sCode) {
        boolean ret = false;
        if (vVector == null)
            return ret;
        if (vVector.isEmpty())
            return ret;
        if (!vVector.contains(sCode))
            return ret;

        ret = true;
        return ret;
    }
    /**
     *  转化时间，如：<p>"2002-3-4" 可转化为 "2002-03-04"</p>
     *
     *@param  origDateTime
     *@return
     */
    public static String formatDate(String origDateTime) {
        String returnValue = "";
        if (origDateTime == null || origDateTime.equals("")) {
            return returnValue;
        }
        try {
            boolean bIsvalid = DateUtil.isValid(origDateTime);
            if (!bIsvalid) {
                return returnValue;
            }
        } catch (Exception e) {
            return returnValue;
        }
        int iYear = origDateTime.indexOf("-");
        int iMonth = origDateTime.indexOf("-", iYear + 1);

        String year = origDateTime.substring(0, iYear);
        String month = origDateTime.substring(iYear + 1, iMonth);
        String day = origDateTime.substring(iMonth + 1);

        returnValue = year + "-" + addZero(month, 2) + "-" + addZero(day, 2);

        return returnValue;
    }
    
    public static String formatText(String origString)
    {
    	if ((origString == null) || (origString.equalsIgnoreCase("")))
    		return "";
    	else	
    		return replace(origString,"\r\n","<br>");
    }
    /**
     *  转化时间，如：<p>"2002-03-04 11:35:00" 可转化为 "20020304113500"</p>
     *
     *@param  origDateTime
     *@return
     */
    public static String formatDatetimeLink(String origDateTime) {

        String returnValue = "";
        if (origDateTime == null || origDateTime.equals("")) {
            return returnValue;
        }
        try {
            boolean bIsvalid = DateUtil.isValid(origDateTime);
            if (!bIsvalid) {
                return returnValue;
            }
        } catch (Exception e) {
            return returnValue;
        }
        int iYear = origDateTime.indexOf("-");
        int iMonth = origDateTime.indexOf("-", iYear + 1);
        int iDay = origDateTime.indexOf(" ", iMonth + 1);
        int iHour = origDateTime.indexOf(":", iDay + 1);
        int iMinute = origDateTime.indexOf(":", iHour + 1);

        String year = origDateTime.substring(0, iYear);
        String month = origDateTime.substring(iYear + 1, iMonth);
        String day = origDateTime.substring(iMonth + 1, iDay);
        String hour = origDateTime.substring(iDay + 1, iHour);
        String minute = origDateTime.substring(iHour + 1, iMinute);
        String second = origDateTime.substring(iMinute + 1);

        returnValue = year + month + day + hour + minute + second;

        return returnValue;
    }
    /**
     *  获得ip地址
     *
     *@return    stout/192.168.0.210
     */
    public static String getClientIp(HttpServletRequest req) {
        String retIp = "";
        retIp = req.getRemoteAddr();
        return retIp;
    }
    /**
     * @return String
     * @param req javax.servlet.http.HttpServletRequest
     * @param ParamName java.lang.String
     * @exception java.lang.Exception 异常说明。
    */
    public static double getDouble(HttpServletRequest req, String ParamName) {

        return strToDouble(getString(req, ParamName));
    }
    /**
     * @return String
     * @param req javax.servlet.http.HttpServletRequest
     * @param ParamName java.lang.String
     * @exception java.lang.Exception 异常说明。
    */
    public static int getInt(HttpServletRequest req, String ParamName) {

        return strToInt(getString(req, ParamName));
    }
    //下面函数用于页面bean和dadabean之间得数据转换
    public static String getString(String str) {

        if (str != null) {
            return str.trim();
        } else {
            return "";
        }
    }
    /**
     * @return String
     * @param req javax.servlet.http.HttpServletRequest
     * @param ParamName java.lang.String
     * @exception java.lang.Exception 异常说明。
    */
    public static String getString(HttpServletRequest req, String ParamName) {

        String query = req.getParameter(ParamName);

        query = parseStringByOs(query);

        if (query != null) {
            return query.trim();
        } else {
            return "";
        }
    }
    public static String getValidDate(String str) {

        String returnValue = "";
        if (str == null || str.equals("")) {
            return returnValue;
        }
        try {
            boolean bIsvalid = DateUtil.isValid(str);
            if (!bIsvalid) {
                return returnValue;
            }
        } catch (Exception e) {
            return returnValue;
        }
        int iYear = str.indexOf("-");
        int iMonth = str.indexOf("-", iYear + 1);

        String year = String.valueOf(strToInt(str.substring(0, iYear)) + 1);
        String month = str.substring(iYear + 1, iMonth);
        String day = str.substring(iMonth + 1);

        returnValue = year + "-" + addZero(month, 2) + "-" + addZero(day, 2);

        return returnValue;
    }
    /**
    *  转换数据，如：<p>"20.0" 可转化为 "20"</p>
    * <p>"test.exe" 可转化为 "test"</p>
    *
    *@param  storNum
    *@return
    */
    public static String moveDot(String storNum) {
        String returnValue = "";
        if (storNum == null || storNum.equals("")) {
            return returnValue;
        }
        int iDot = storNum.indexOf(".");
        if (iDot == -1) {
            return storNum;
        }
        returnValue = storNum.substring(0, iDot);

        return returnValue;
    }
    /**
    * 解决中英文操作系统下，通过href传递的字串
    * add by cary@2001-10-28
    * @param str 字符串
    * @return 转化后的字符串
    */
    public static String parseStringByOs(String str) {
		return "";	    
    }
    public static String replace(
        String source,
        String oldString,
        String newString) {
        if (source == null) {
            return null;
        }
        StringBuffer output = new StringBuffer();
        int lengOfsource = source.length();
        int lengOfold = oldString.length();
        int posStart = 0;
        int pos;
        while ((pos = source.indexOf(oldString, posStart)) >= 0) {
            output.append(source.substring(posStart, pos));
            output.append(newString);
            posStart = pos + lengOfold;
        }
        if (posStart < lengOfsource) {
            output.append(source.substring(posStart));
        }
        return output.toString();
    }
    //此函数将一字符串依照指定子串分割，成功则传回数组，否则传回null
    public static String[] separateStr(String a_Src, String a_needle) {

        String[] sNoElement = null;
        if (a_Src == null || a_Src.equals(""))
            return sNoElement;
        if (a_needle == null || a_needle.equals(""))
            return sNoElement;

        String a_SrcTmp = "";
        Vector vSrcTmp = new Vector();

        int iFlag = a_Src.indexOf(a_needle);
        while (iFlag != -1) {
            a_SrcTmp = a_Src.substring(0, iFlag);
            vSrcTmp.addElement(a_SrcTmp);
            a_Src = a_Src.substring(iFlag + a_needle.length());
            iFlag = a_Src.indexOf(a_needle);
        }
        vSrcTmp.addElement(a_Src);
        //System.out.println(a_Src);
        String[] rtn = new String[vSrcTmp.size()];
        //System.out.println(vSrcTmp.size());
        int iii = 0;
        while (iii < vSrcTmp.size()) {
            rtn[iii] = (String) vSrcTmp.get(iii);
            iii++;
            //System.out.println(rtn[iii-1]);
        }
        //System.out.println(iii);
        return rtn;
    }
    public static double strToDouble(String oldStr) {

        return strToDouble(oldStr, 0);
    }
    public static double strToDouble(String oldStr, double dblDefault) {

        try {
            return Double.parseDouble(oldStr.trim());
        } catch (Exception e) {

            return dblDefault;
        }

    }
    public static int strToInt(String oldStr) {

        return strToInt(oldStr, 0);
    }
    public static int strToInt(String oldStr, int intDefault) {

        try {
            return Integer.parseInt(oldStr.trim());
        } catch (Exception e) {

            return intDefault;
        }
    }

    /**
    * 将xls文件中*****转换为""
    * add by stout@2003-10-10
    * @param str 字符串
    * @return 转化后的字符串
    */
    public static String formatXlsStr(String str) {
        String mark = "*****"; 
        String retStr = "";

        if (str != null) {
            retStr = str.trim();
            retStr = replace(retStr, mark, "");
        }
        return retStr;
    }
	public static TreeSet arrayToSet(int [] ary) {
	
			HashSet setTmp = new HashSet();
        
			for (int i=0; i<ary.length; i++){
	       
				setTmp.add(new Integer(ary[i])) ;
			}

			return new TreeSet(setTmp);
	}
	
	/**
	 * 是否是空字符串
	 * 
	 * @param str
	 * @return true 为空
	 */
	public static boolean isNullStr(String str){
		if ("".equals(str)){
			return true;
		}
		if (str == null){
			return true;
		}
		return false;
//		return "".equals(str())||str == null;
	}
	
	/**
	 * 显示价格, 补零用
	 * @param price
	 * @param fractionSize
	 * @return
	 */
	public static String showPrice(double price, int fractionSize){
		if (price == Value.NULL_DOUBLE)
			return "";
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(fractionSize);
		return nf.format(price);
	}
	

	public static String showPrice(String price) throws Exception {
		double l_Price;
		try {
			//l_Price = Double.parseDouble(price);
            java.math.BigDecimal b = new java.math.BigDecimal(price);//处理在0.005的情况
            double f1 = b.setScale(2, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
			String numberStr = showPrice(f1, 2);
			return numberStr;
		} catch (NumberFormatException e) {
			return price;
		}
	}

    public static String showPrice4(String price) throws Exception {
        double l_Price;
        try {
          //  l_Price = Double.parseDouble(price);
            java.math.BigDecimal b = new java.math.BigDecimal(price);
            double f1 = b.setScale(4, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
            String numberStr = showPrice(f1, 4);
            return numberStr;
        } catch (NumberFormatException e) {
            return price;
        }
    }
	
    public static String showCount(String count) throws Exception {
        double l_Price;
        try {
           // l_Price = Double.parseDouble(count);
            java.math.BigDecimal b = new java.math.BigDecimal(count);
            double f1 = b.setScale(3, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
            String numberStr = showPrice(f1, 3);
            return numberStr;
        } catch (NumberFormatException e) {
            return count;
        }
    }
	
	
	public static boolean isNullStringArray(String[] array){
		if (array == null)
			return true;
			
		int count = 0;
		for(int i = 0; i < array.length; i++ ){
			if(isNullStr(array[i])){
				count++;
			}
		}
		return count == array.length;
	}
	
	public static String replaceFirst(String orgStr, String oldString, String newString) throws Exception
	{
		if (orgStr == null) {
			return null;
		}
		StringBuffer output = new StringBuffer();
		int lengOfsource = orgStr.length();
		int lengOfold = oldString.length();
		int posStart = 0;
		int pos;
		if((pos = orgStr.indexOf(oldString, posStart)) >= 0)
		{
			output.append(orgStr.substring(posStart, pos));
			output.append(newString);
			posStart = pos + lengOfold;
		}
		if (posStart < lengOfsource) {
			output.append(orgStr.substring(posStart));
		}
		return output.toString();
		 
	}
	
    public static String replaceSql(String orgStr) throws Exception
    {
        String mReturn = "";
        mReturn = orgStr;
        String[][] replaceStrs = new String[][] {{"'",""},{"?",""},{"？",""},{"，",""}};
        for(int i=0;i<replaceStrs.length;i++)
        {
            mReturn = replaceSqlString(mReturn,replaceStrs[i][0],replaceStrs[i][1]);
        }
        return mReturn;
    }
	
    public static String replaceSqlString(String orgStr, String oldString, String newString) throws Exception
    {
        if (orgStr == null) {
            return null;
        }
        
        StringBuffer output = new StringBuffer();
        int lengOfsource = orgStr.length();
        int lengOfold = oldString.length();
        int posStart = 0;
        int pos;
        while((pos = orgStr.indexOf(oldString, posStart)) >= 0)
        {
            output.append(orgStr.substring(posStart, pos));
            output.append(newString);
            posStart = pos + lengOfold;
        }
        if (posStart < lengOfsource) {
            output.append(orgStr.substring(posStart));
        }
        return output.toString().toUpperCase();
         
    }	
	
}